package com.hrzyit.whistle.cases.ui.activity

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder
import cn.bingoogolapple.refreshlayout.BGARefreshLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.hrzyit.base.common.BaseConstant
import com.hrzyit.base.data.protocol.ApiPageInfo
import com.hrzyit.base.ext.startLoading
import com.hrzyit.base.ui.activity.BaseMvpActivity
import com.hrzyit.base.ui.adapter.BaseRecyclerViewAdapter
import com.hrzyit.base.utils.AppPrefsUtils
import com.hrzyit.base.utils.RolePermissionUtils
import com.hrzyit.provider.routers.RouterPath
import com.hrzyit.whistle.cases.R
import com.hrzyit.whistle.cases.common.CaseConstant
import com.hrzyit.whistle.cases.data.bean.AuthMsgEntityVo
import com.hrzyit.whistle.cases.data.bean.CaseInfoEntity
import com.hrzyit.whistle.cases.event.CaseAppendApproveEvent
import com.hrzyit.whistle.cases.injection.component.DaggerCaseCenterComponent
import com.hrzyit.whistle.cases.injection.module.CaseCenterModule
import com.hrzyit.whistle.cases.injection.module.CaseTypeModule
import com.hrzyit.whistle.cases.presenter.CaseListPresenter
import com.hrzyit.whistle.cases.presenter.view.CaseListView
import com.hrzyit.whistle.cases.ui.adapter.CaseAdapter
import com.hrzyit.whistle.cases.widgets.CaseApproveEditPopup
import com.hrzyit.whistle.cases.widgets.CaseApproveViewPopup
import com.kennyc.view.MultiStateView
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.activity_summary_case.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * 案件汇总界面
 * @author YangWei
 * @date 2019/3/26
 */
@Route(path = RouterPath.CasesCenter.PATH_SUMMARY_CASE)
class SummaryCaseActivity : BaseMvpActivity<CaseListPresenter>(),
    CaseListView, BGARefreshLayout.BGARefreshLayoutDelegate {

    /**
     * 获取案件批示详情回调接口
     */
    override fun onGetCaseAuthInfoSuccess(result: AuthMsgEntityVo) {
        authMsgEntityVoOld = result
        when (result.isAuth) {
            0 -> {
                // (未批示)弹出待批示窗口
                when (RolePermissionUtils.isLeader()) {
                    true -> {
                        showApproveEditView(result)
                    }
                }
            }
            else -> {
                // (有批示)弹出批示详情窗口
                showApproveView(result)
            }
        }
    }

    /**
     * (未批示)弹出待批示窗口
     */
    private fun showApproveEditView(result: AuthMsgEntityVo) {
        caseApproveEditPopup = CaseApproveEditPopup(this@SummaryCaseActivity, mPresenter)
        // 将获取到批示详情信息传入到编辑窗口
        caseApproveEditPopup.authMsgEntityVo = result
        XPopup.Builder(this@SummaryCaseActivity)
            .asCustom(caseApproveEditPopup).show()
    }

    /**
     * (有批示)弹出批示详情窗口
     */
    private fun showApproveView(result: AuthMsgEntityVo) {
        caseApproveViewPopup = CaseApproveViewPopup(this@SummaryCaseActivity, mPresenter)
        caseApproveViewPopup.authMsgEntityVo = result
        XPopup.Builder(this@SummaryCaseActivity)
            .asCustom(caseApproveViewPopup)
            .show()
    }

    // 批示弹出窗口
    private lateinit var caseApproveEditPopup: CaseApproveEditPopup
    private lateinit var caseApproveViewPopup: CaseApproveViewPopup
    private lateinit var authMsgEntityVoOld: AuthMsgEntityVo

    // 案件数据列表适配器
    private lateinit var caseListAdapter: CaseAdapter

    private var mCurrentPage: Int = 1

    private var mMaxPage: Int = 0

    //主界面Fragment
//    private val mCaseInfoFragment by lazy { CaseInfoFragment() }

    // 多状态视图

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_summary_case)
        EventBus.getDefault().register(this)

        initView()
        initRefreshLayout()
        loadData()
    }

    val userId = AppPrefsUtils.getLong(BaseConstant.KEY_SP_USER_TOKEN)
    /**
     * 初始化视图
     */
    private fun initView() {

        // 0. 获取案件列表控件：mCaseListRv
        // 1. 设置案件列表控件属性
        mCaseListRv.layoutManager = LinearLayoutManager(this) // 线性布局
        mCaseListRv.setHasFixedSize(true)
        // 2. 设置适配器
        caseListAdapter = CaseAdapter(this)
        mCaseListRv.adapter = caseListAdapter

        // 3. 配置适配器中组件的事件
        caseListAdapter.setOnItemClickListener(object :
            BaseRecyclerViewAdapter.OnItemClickListener<CaseInfoEntity> {

            override fun onItemClick(view: View, item: CaseInfoEntity?, position: Int) {
                when (view.id) {
                    R.id.mLeaderApproveIv -> {
                        // 获取批示详情,若案件已批示弹出详情;若未批示过,弹出批示编辑窗口
                        mPresenter.getCaseAuthInfo(item!!.id, userId)
                    }
                    R.id.mCaseItemList -> {
                        // 跳转到案件详情页面
                        startActivity<CaseInfoActivity>("id" to item!!.id)
                    }
                }
            }
        })

    }

    /**
     * 初始化刷新视图
     */
    private fun initRefreshLayout() {
        mRefreshLayout.setDelegate(this)
        val viewHolder = BGANormalRefreshViewHolder(this, true)
        viewHolder.setLoadMoreBackgroundColorRes(R.color.common_bg)
        viewHolder.setRefreshViewBackgroundColorRes(R.color.common_bg)
        mRefreshLayout.setRefreshViewHolder(viewHolder)
    }

    /**
     * 加载数据
     */
    private fun loadData() {

        // 打开加载多状态视图-加载状态
        mMultiStateView.startLoading()
        // 根据案件类型获取案件列表
        mPresenter.selectCaseListByCaseType(
            CaseConstant.CASE_SORT_ALL,
            mCurrentPage,
            BaseConstant.PAGE_SIZE_DEFAULT
        )

    }

    /**
     * Dagger 注入
     */
    override fun injectComponent() {

        DaggerCaseCenterComponent.builder()
            .activityComponent(mActivityComponent)
            .caseTypeModule(CaseTypeModule())
            .caseCenterModule(CaseCenterModule())
            .build()
            .inject(this)

        // 初始化 Presenter.View
        mPresenter.mView = this
    }

    /**
     * 获取案件分类对应的案件数据列表分页回调
     */
    override fun onGetCaseInfoListSuccess(result: ApiPageInfo<CaseInfoEntity>) {
        //  关闭上拉、下拉动画
        mRefreshLayout.endLoadingMore()
        mRefreshLayout.endRefreshing()
        val list = result.records
        if (list != null && list.isNotEmpty()) {
            mMaxPage = result.pages
            if (mCurrentPage == 1) {
                caseListAdapter.setData(result.records!!)
            } else {
                caseListAdapter.dataList.addAll(result.records!!)
                caseListAdapter.notifyDataSetChanged()
            }
            // 多状态视图-内容显示状态
            mMultiStateView.viewState = MultiStateView.VIEW_STATE_CONTENT

        } else {
            // 多状态视图-无数据显示状态
            mMultiStateView.viewState = MultiStateView.VIEW_STATE_EMPTY
        }
    }


    /**
     * 获取案件详情信息回调
     */
//    override fun onGetCaseInfoSuccess(result: CaseDetailInfoEntity) {
//        Log.d("案件详情信息", result.toString())
//    }

    /**
     * 上拉加载更多
     */
    override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout?): Boolean {
        return if (mCurrentPage < mMaxPage) {
            mCurrentPage++
            loadData()
            true
        } else {
            false
        }
    }

    /**
     * 下拉刷新:第一页
     */
    override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout?) {
        mCurrentPage = BaseConstant.PAGE_CURRENT_DEFAULT
        loadData()
    }

    /**
     * 保存批示信息完成
     */
    override fun onGetSaveAuthMsgSuccess(result: Boolean) {
        when (result) {
            true -> {
                toast("批示信息保存")
                caseApproveEditPopup.dismiss()
                mCurrentPage = BaseConstant.PAGE_CURRENT_DEFAULT
                loadData()
            }
            else -> {
                toast("批示信息保存失败")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    /**
     * 批示查看页面跳转到批示追加事件处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCaseAppendApproveEvent(caseAppendApproveEvent: CaseAppendApproveEvent) {
        showApproveEditView(caseAppendApproveEvent.authMsgEntityVo)
    }

}